/**
 *  last update 2015.05.21
 *  Faeple.com
 */
var noti_count = 0;
/* 30초에 한번씩 알림 가져오기 */
setTimeout(function(){getNotificationCount();},1000);
setTimeout(function(){getNewMessageCount();},1000);
setInterval(getNotificationCount, 30000);
setInterval(getNewMessageCount, 30000);
/* 읽지 않은 메시지 갯수 가져오기 */
function getNewMessageCount(){
	$.ajax({
	    type : "get"
	    , url : "/getNewMessageCount?idx="+userIdx
	    , dataType : "text"
	    , timeout : 5000
	    , success : function(response) {
	    	$("#messageCount").html(response);
	    	$("#messageCountM").html(response);
	    	if(response == 0){
	    		$("#messageCount").hide();
	    		$("#messageCountM").hide();
	    		$("#messageBtn").attr("title", "확인하지 않은 메시지 없음");
	    	}else{
	    		$("#messageCount").show();
	    		$("#messageCountM").show();
	    		$("#messageBtn").attr("title", "새로운 메시지 "+response+"개");
	    	}
	    }
	});
}

/* 읽지 않은 알림 갯수 가져오기 */
function getNotificationCount(){
	$.ajax({
	    type : "get"
	    , url : "/getNotiCount?idx="+userIdx
	    , dataType : "text"
	    , timeout : 5000
	    , error : function(request, status, error) {
	    	
	    }
	    , success : function(response) {
	    	$("#notiCount").html(response);
	    	$("#notiCountM").html(response);
	    	if(response == 0){
	    		$("#notiCount").hide();
	    		$("#notiCountM").hide();
	    		$("#notiBtn").attr("title", "확인하지 않은 알림 없음");
	    	}else{
	    		$("#notiCount").show();
	    		$("#notiCountM").show();
	    		$("#notiBtn").attr("title", "새로운 알림 "+response+"개");
	    	}
	    }
	});
}

function getnotiAllCount(){
	var count = 0;
	$.ajax({
		type: "post",
		async: false,
		url: "/getNotiAllCount?idx="+userIdx,
		dataType : "text",
		timeout: 5000,
		success : function(response){
			count = response;
			
		}
	});
	return count;
}

/* 알림 내용 가져오기 */
function getNotiList(){
	if(noti_index==0){
		$("#notification-list").empty();
	}
	$.ajax({
	    type : "get"
	    , url : "/getNotiList?idx="+userIdx+"&index="+noti_index
	    , dataType : "json"
	    , timeout : 5000
	    , error : function(request, status, error) {
	    	$("#noti-fail-message").show();
	    }
	    , success : function(response) {
	    	if(!response.length == 0){
	    		for(var i=0;i<response.length;i++){
	    			var html = "<li><a href='/"+response[i].author_id+"' class='refer_profileImg'><span></span><img src='/resources/upload/profile/thumbnail/"+response[i].refer_profileImage+"'></a><span class='noti-content'>"+response[i].description+"<span class='noti-date'>"+timeleft(response[i].create_date)+"</span></span>";
	    			if(response[i].type == "following"){
	    				html += "<button type='button' title='팔로우' class='noti_follow' onclick='noti_follow(this, \"follow\", "+response[i].author_idx+")'><i class='ion-plus-round' style='font-size:14px;'></i>&nbsp;<i class='ion-person' style='font-size:16px;'></i></button></li>";
	    			}else{
	    				html += "<a href='/p/"+response[i].refer_url+"' class='refer_postImg'><span></span><img src='/resources/upload/post/thumbnail/"+response[i].refer_img+"'></a></li>";
	    			}
	    			$("#notification-list").append(html);
		    	}
	    		if(response.length > 7){
	    			$("#more-notification").show();
	    		}else{
	    			$("#more-notification").hide();
	    		}
	    		$("#notiCount").hide();
	    		$("#notiDis").attr("title", "확인하지 않은 알림 없음");
	    	}else{
	    		if(noti_index == 0){
	    			$("#noti-not-message").show();
	    			$("#clearNoti").hide();
	    		}
	    		$("#more-notification").hide();
	    	}
	    }
	    , beforeSend: function() {
	    	$('#notifications-loading').show(); 
	    }
	    , complete: function() {
	    	$('#notifications-loading').hide();
	    }
	});
}

function noti_follow(obj, type, idx) {
	var data = "following_idx="+idx;
	if (type == "follow") {
	  	$(obj).html("<div class='spinner small'></div>");
	  	setTimeout(function(){
	  		$.ajax({
	                type: "post",
	                url: "/follow",
	                data: data,
	                dataType: "text",
	                timeout: 5000,
	                error: function () {
	                    alertShow("danger", "다시 시도해주세요", 2000);
	                },
	                success: function (response) {
	                    if (response == "success") {
	                        $(obj).addClass("active").html("<i class='ion-checkmark' style='font-size:13px;'></i>&nbsp;<i class='ion-person' style='font-size:16px;'></i>").attr("onclick", "noti_follow(this, 'unfollow', "+idx+");").hide().fadeIn();
	                    } else if (response == "closed") {
	                        alertShow("danger", "팔로우를 받지 않는 사용자입니다", 2000);
	                        $(obj).html("<i class='ion-plus-round' style='font-size:14px;'></i>&nbsp;<i class='ion-person' style='font-size:16px;'></i>").hide().fadeIn();
	                    } else if (response == "role") {
	                        alertShow("danger", "로그인이 필요합니다", 2000);
	                        $(obj).html("<i class='ion-plus-round' style='font-size:14px;'></i>&nbsp;<i class='ion-person' style='font-size:16px;'></i>").hide().fadeIn();
	                    } else {
	                        alertShow("info", "이미 팔로우 하였습니다.", 2000);
	                        $(obj).html("<i class='ion-plus-round' style='font-size:14px;'></i>&nbsp;<i class='ion-person' style='font-size:16px;'></i>").hide().fadeIn();
	                    }
	                }
	            });
	  	}, 500);
	} else {
	  	$(obj).html("<div class='spinner small'></div>");
	  	setTimeout(function(){
	  		$.ajax({
	                type: "post",
	                url: "/unFollow",
	                data: data,
	                dataType: "text",
	                timeout: 5000,
	                error: function () {
	                    alertShow("danger", "다시 시도해주세요", 2000);
	                },
	                success: function (response) {
	                    if (response == "fail") {
	                        alertShow("danger", "다시 시도해주세요", 2000);
	                        $(obj).html("<i class='ion-plus-round' style='font-size:14px;'></i>&nbsp;<i class='ion-person' style='font-size:16px;'></i>").hide().fadeIn();
	                    } else {
	                        $(obj).removeClass("active").attr("onclick", "noti_follow(this, 'follow', "+idx+");").html("<i class='ion-plus-round' style='font-size:14px;'></i>&nbsp;<i class='ion-person' style='font-size:16px;'></i>").hide().fadeIn();
	                    }
	                }
	            });
	  	}, 500);
	}
}
	
function notiClear(){
	if(confirm("모든 알림내역을 지우시겠습니까?")){
		$.ajax({
			type : "get"
			, url : "/notiClear?idx="+userIdx
			, dataType : "text"
			, timeout : 5000
			, error : function(x,e) {
				alertShow("danger","다시 시도해주세요", 2000);
			}
			, success : function(response) {
				if(response == "execute"){
					$("#notification-list").html("<p style='text-align: center; font-weight:bold;'>표시할 알림이 없습니다</p>");
					$("#notiDis").attr("title", "확인하지 않은 알림 없음");
					$("#clearNoti").hide();
					$("#more-notification").hide();
				}else{
					alertShow("danger","다시 시도해주세요", 2000);
				}
			}
			, beforeSend: function() {
				$('#ajax_indicator2').show().fadeIn('fast'); 
			}
			, complete: function() {
				$('#ajax_indicator2').fadeOut('fast');
			}
		});
	}
}

function imagePreview(input){
	var fileList = input.files;
	var imgPreview = $("#imagePreview");
	$("#write-guide-message1").hide();
	try{
		if(fileList.length > 8){
        	alert("사진을 8개 이하로 올려주세요");
        	input.value = "";
        }else{
        	var uploadSize = 0;
        	$("input.currentposition").each(function(){
        		if($(this).val() != ""){
        			uploadSize++;
        		}
        	});
        	if(uploadSize+fileList.length > 8){
        		alert("사진을 8개 이하로 올려주세요");
        	}else{
        		var imgSize = imgPreview.children("div").size();
                var bar = $(".progress-bar");
          		var progressBar = $("#progressBar");
          		var postWriteBtn = $("#postWriteBtn");
                $.getScript('/resources/js/jquery.form.js', function(){
            		$("#img-form").ajaxSubmit({
            			statusCode: { 
            				400: function() {
            					$("#imagePreview").empty();
            					alertShow("danger","이미지 업로드에 실패했습니다", 2000);
            				},
            				500: function() {
            					$("#imagePreview").empty();
            					alertShow("danger","이미지 업로드에 실패했습니다.", 2000);
            				}
            			},
            			dataType: "json",
            			beforeSubmit: function() {
            				postWriteBtn.hide();
            				var percentVal = '0%';
            		        bar.width(percentVal);
            		        progressBar.show();
            			},
            			uploadProgress: function(event, position, total, percentComplete) {
            				var percentVal = percentComplete + '%';
            		        bar.width(percentVal);
            		    },
            			success: function(data) {
            				for(var i=0;i<data.length;i++){
            					$("#image"+(imgSize+1)).val(data[i].image);
            					imgSize++;
            				}
            				$("#writeNextStepBtn").show();
            				$("#write-guide-message2").show();
            			},
            			complete: function(){
            				postWriteBtn.show();
            				progressBar.hide();
            			}
            		});
        		});
                
          		var anyWindow = window.URL || window.webkitURL;

                for(var i = 0; i < fileList.length; i++){
                	var objectUrl = anyWindow.createObjectURL(fileList[i]);
                	imgPreview.append("<div data-index='"+(i+1)+"'><img src='" + objectUrl + "' /><i class='fa fa-times' title='삭제' onclick='uploadImgTrash(this)'></i></div>");
                	//window.URL.revokeObjectURL(fileList[i]);
                }
                imgPreview.sortable("refresh");
                
                $("#uploadImageSize").html(imgPreview.children("div").size());
                if(imgPreview.children("div").size() == 8){
                	$("#imageUploadBtn").hide();
                }
                
        	}
        }
	}catch(e){
		//$("#postWriteBtn").hide();
		$("#catchImgUploadBtn").show();
	}  
}

function postWrite(){
	if($("#inputColor").val() == ""){
		var image = new Image;
		image.src = "resources/upload/post/"+$("#image1").val();
		$.getScript('/resources/js/color-thief.js', function(){
			var colorThief = new ColorThief();
			$(image).on("load", function(){
		        var color = colorThief.getColor(image);
	        	$.getScript('/resources/js/ntc.js', function(){
	        		//console.log(color);
	        		var hex = "#"+toHex(color[0])+toHex(color[1])+toHex(color[2]);
	        		//console.log(hex);
	        		var colorName = ntc.name(hex);
	            	//console.log(colorName[1]);
	            	$("#inputColor").val(colorName[1]);
	            	//console.log($("#inputColor").val());
	            	postWriteSubmitAjax();
	        	});
			});
		});
	}else{
		postWriteSubmitAjax();
	}
}

function postWriteSubmitAjax(){
	var bar = $(".progress-bar");
	var progressBar = $("#progressBar");
	var postWriteBtn = $("#postWriteBtn");
	var tagUser;
	if($("#inputContent").val() == ""){
		alertShow("info","설명을 입력해 주세요", 2000);
		//$("#inputContent").focus();
		return false;
	}else{
		tagUser = $("#inputContent").val().parseTagUser();
		//console.log(tagUser);
		if(tagUser != null) tagUser = tagUser.toString();
		$("#tagUser").val(tagUser);
	}
	if($("#inputContent").val().length > 400){
		alertShow("info","설명이 초과되었습니다", 2000);
		return false;
	}
	
	if($("#image1").val() == ""){
		alertShow("info","사진을 하나라도 업로드 해주세요", 2000);
		return false;
	}
	
	$("#inputTag").val(getHashtagParse());
	$.getScript('/resources/js/jquery.form.js', function(){
		$("#write-form").ajaxSubmit({
			statusCode: { 
				400: function() {
					alertShow("danger","오류가 발생하였습니다", 2000);
				},
				500: function() {
					alertShow("danger","오류가 발생하였습니다", 2000);
				}
			},
			beforeSubmit: function() {
				postWriteBtn.hide();
				var percentVal = '0%';
		        bar.width(percentVal);
		        progressBar.show();
			},
			uploadProgress: function(event, position, total, percentComplete) {
				var percentVal = percentComplete + '%';
		        bar.width(percentVal);
		    },
			success: function(data) {
				var percentVal = '100%';
		        bar.width(percentVal);
				if(data != "role" && data != "tag"){
	    			$("#write-dialog").modal("hide");
	    			alertShow("success","<i class='fa fa-check'></i>&nbsp;게시글이 성공적으로 작성되었습니다&nbsp;<a href='/p/"+data+"' class='alert-link' style='font-weight:bold;'>확인하러가기</a>", null);
	    			postWriteFormReset();
				}else if(data == "role"){
					alertShow("danger","로그인이 필요합니다", 2000);
				}else{
					alertShow("danger","사용자 태그가 잘못되었습니다. 사용자 아이디를 확인해 주세요", 2000);
					$("#inputContent").next().css({"border-color":"#a94442","box-shadow":"inset 0 1px 1px rgba(0, 0, 0, .075)"});
				}
			},
			complete: function(){
				postWriteBtn.show();
				progressBar.hide();
			}
		});
	});
}

function remainContent(){
	var size = $("#inputContent").val().length;
	if(size > 400){
		alert("설명이 초과되었습니다.");
	}else if(size > 370){
		$("#content-length").css("color","#FF0000");
	}else{
		$("#content-length").css("color","#ccc");
	}
	$("#content-length").html(size);
}
	
function uploadImgTrash(obj){
	var imgPreview = $("#imagePreview");
	var index = $(obj).parent().index()+1;
	if(index == 8){
		$("#image8").val("");
	}else{
		for(index;index<9;index++){
			$("#image"+index).val($("#image"+index).next().val());
		}
	}
	$(obj).parent().remove();
	imgPreview.sortable("refresh");
	var imgUploadSize = imgPreview.children("div").size();
	$("#uploadImageSize").html(imgUploadSize);
	$("#imageUploadBtn").show();
	if(imgUploadSize == 0){
		$("#writeNextStepBtn").hide();
		$("#write-guide-message2").hide();
	}
}

$(function(){
	
	$("#notifications-modal").on("shown.bs.modal", function(){
		getNotiList();
	}).on("hide.bs.modal", function(){
		noti_index = 0;
		noti_count = 0;
	});
	
	if(userGender == "female"){
		$("input:radio[name='gender'][value='womens']").attr("checked",true);
		$("#post-category").selectpicker('refresh');
	}else{
		$("input:radio[name='gender'][value='mens']").attr("checked",true);
		$("#post-category").children("option").eq(0).html("남성의류").val("m_clothes").next().html("남성신발").val("m_footwear").next().html("남성가방").val("m_bag").next().html("남성악세사리").val("m_accessory").next().html("남성뷰티").val("m_beauty");
		$("#post-category").selectpicker('refresh');
	}
	
	$("input:radio[name=gender]").on("ifChecked", function(){
		if(this.value == "womens"){
			$("#post-category").children("option").eq(0).html("여성의류").val("w_clothes").next().html("여성신발").val("w_footwear").next().html("여성가방").val("w_bag").next().html("여성악세사리").val("w_accessory").next().html("여성뷰티").val("w_beauty");
			$("#post-category").selectpicker('refresh');
		}else{
			$("#post-category").children("option").eq(0).html("남성의류").val("m_clothes").next().html("남성신발").val("m_footwear").next().html("남성가방").val("m_bag").next().html("남성악세사리").val("m_accessory").next().html("남성뷰티").val("m_beauty");
			$("#post-category").selectpicker('refresh');
		}
	});
	
	/*$("#post-category").change(function(){
		if($(this).val() == "w_beauty" || $(this).val() == "m_beauty"){
			$("#color-form").hide("slide",{direction: 'up'},800);
		}else{
			$("#color-form").show("slide",{direction: 'up'},800);
		}
	});*/
		
	$("#write-dialog").on("show.bs.modal", function(){
		$("input:radio[name=gender]").iCheck('update');
		$.ajax({
			type : "get"
		    , url : "/getTagUserList"
		    , dataType : "json"
		    , timeout : 5000
		    , success : function(response) {
		    	var users = [];
		    	for(var i=0;i<response.length;i++){
		    		users.push({"name":response[i].name,"username":response[i].id,"image":"/resources/upload/profile/thumbnail/"+response[i].profileImage});
		    	}
		    	$("#inputContent").next().mention({
	    			sensitive: true,
					users: users
				});
		    }
		});
	}).on("hide.bs.modal", function(){
		postWriteFormReset();
	});
	
	$("#colorPicker div").click(function(){
		$("#colorPicker div").each(function(){
			$(this).empty();
		});
		if($(this).data("color") == "white" || $(this).data("color") == "yellow" || $(this).data("color") == "beige"){
			$(this).html("<i class='fa fa-check' style='color:#000; font-size:16px;'></i>");
		}else{
			$(this).html("<i class='fa fa-check' style='color:#fff; font-size:16px;'></i>");
		}
		$("#inputColor").val($(this).data("color"));
	});
	
	$("#imagePreview").disableSelection();
	$("#imagePreview").sortable({
		placeholder: "ui-state-highlight",
		revert: true,
		zIndex: 9999,
		start: function(e, ui) {
	        $(this).attr('data-previndex', ui.item.index()+1);
	    },
		update: function(e, ui) {
			var newIndex = ui.item.index()+1;
			var oldIndex = parseInt($(this).attr('data-previndex'));
			$(this).removeAttr('data-previndex');
			
			var temp2 = $("#image"+newIndex).val();
			$("#image"+newIndex).val($("#image"+oldIndex).val());
			
			if(newIndex < oldIndex){
				if(oldIndex-newIndex == 1){
					$("#image"+oldIndex).val(temp2);
				}else{
					var total = oldIndex-newIndex;
					for(var i=0;i<total;i++){
						if(i == total-1){
							$("#image"+(oldIndex-i)).val(temp2);
						}else{
							$("#image"+(oldIndex-i)).val($("#image"+(oldIndex-i)).prev().val());
						}
					}
				}
			}else{
				if(newIndex-oldIndex == 1){
					$("#image"+oldIndex).val(temp2);
				}else{
					var total = newIndex-oldIndex;
					for(var i=0;i<total;i++){
						if(i == total-1){
							$("#image"+(oldIndex+i)).val(temp2);
						}else{
							$("#image"+(oldIndex+i)).val($("#image"+(oldIndex+i)).next().val());
						}
					}
				}
			}
		}
	});
	
	$.getScript('/resources/js/jquery.form.js', function(){
		var imgSize = $("#imagePreview").children("div").size();
        var bar = $(".progress-bar");
    	var progressBar = $("#progressBar");
    	var postWriteBtn = $("#postWriteBtn");
    	var imgPreview = $("#imagePreview");
  		$("#img-form").ajaxForm({
  			statusCode: { 
  				400: function() {
  					alertShow("danger","오류가 발생하였습니다", 2000);
  				},
  				500: function() {
  					alertShow("danger","오류가 발생하였습니다", 2000);
  				}
  			},
  			dataType: "json",
  			beforeSubmit: function() {
  				postWriteBtn.hide();
  				var percentVal = '0%';
  		        bar.width(percentVal);
  		        progressBar.show();
  			},
  			uploadProgress: function(event, position, total, percentComplete) {
  				var percentVal = percentComplete + '%';
  		        bar.width(percentVal);
  		    },
  			success: function(data) {
  				for(var i=0;i<data.length;i++){
  					$("#image"+(imgSize+1)).val(data[i].image);
  					imgPreview.append("<div><img src='/resources/upload/post/thumbnail/" + data[i].image + "' /></div>");
  					imgSize++;
  				}
  				imgPreview.sortable("refresh");
                $("#uploadImageSize").html(imgPreview.children("div").size());
                if(imgPreview.children("div").size() == 8){
                	$("#imageUploadBtn").hide();
                }
                $("#writeNextStepBtn").show();
  			},
  			complete: function(){
  				postWriteBtn.show();
  				progressBar.hide();
  				$("#catchImgUploadBtn").hide();
  			}
  		});
	});
	
	$("#inputContent").emojiarea({wysiwyg: true, button: '#write-emoji-btn', 'setClass':'write'});
	$(".emoji-wysiwyg-editor.write").keyup(function(){
		var size = $("#inputContent").val().length;
		if(size > 370){
			$("#content-length").css("color","#FF0000");
		}else{
			$("#content-length").css("color","#ccc");
		}
		$("#content-length").html(size);
	});
	
	$("#inputTag").keydown(function(event){
		if(event.keyCode == 190 || event.keyCode == 191){
			return false;
		}
	});
	//$("#inputTag").select2({tags:[],tokenSeparators: [",", " "]});
});

function writeStep(type){
	if(type == "next"){
		$("#write-step1-form").hide();
		$("#write-step2-form").show();
	}else{
		$("#write-step1-form").show();
		$("#write-step2-form").hide();
	}
}

function toHex(n) {
	n = parseInt(n,10);
	if (isNaN(n)) return "00";
	n = Math.max(0,Math.min(n,255));
	return "0123456789ABCDEF".charAt((n-n%16)/16)+ "0123456789ABCDEF".charAt(n%16);
}

function postWriteFormReset(){
	$("#write-form").each(function(){
		this.reset();
	});
	$("input.currentposition").each(function(){
		$(this).val("");
	});
	$("#inputColor").val("");
	$("#imagePreview").empty();
	$("#uploadImageSize").html("0");
	$(".emoji-wysiwyg-editor.write").empty();
	$("#catchImgUploadBtn").hide();
	//$("#content-length").html("0");
	$("#images").val("");
	$("#inputContent").next().html("");
	$("#write-step1-form").show();
	$("#write-step2-form").hide();
}

//hashtag parsing
function getHashtagParse(){
	var content = $("#inputContent").val().match(/[#]+[A-Za-z0-9가-힣_]+/g);
	if(content != null){
		var hashtag = [];
		$.each(content, function(i, el){
			if($.inArray(el, hashtag) === -1) hashtag.push(el);
		});
		for(var i=0;i<hashtag.length;i++){
			hashtag[i] = hashtag[i].substr(1);
		}
		return hashtag;
	}else{
		return "";
	}
	
	//document.writeln(uniqueNames);

	/*String.prototype.parseHashtag = function() {
		return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
			var tag = t.replace("#","%23")
			return t.link("http://search.twitter.com/search?q="+tag);
		});
	};
	test = "Simon is writing a post about #twitter#javascript and parsing hashtags as URLs";
	document.writeln(test.parseHashtag());*/
}